<template>
  <div class="verify-code-container">
    <div class="header">
      <div class="back-btn" @click="goBack">←</div>
      <h2>请输入验证码</h2>
    </div>
    <div class="phone-info">
      已通过短信发送至：
      <span>{{ phoneNumber }}</span>
      <span class="modify-btn" @click="handleModifyPhone">修改</span>
    </div>
    <div class="code-input-box">
      <input
        v-for="(_, index) in 6"
        :key="index"
        :ref="el => inputRefs[index] = el"
        v-model="codeArray[index]"
        type="text"
        inputmode="numeric"
        pattern="[0-9]*"
        maxlength="1"
        @input="e => handleCodeInput(e, index)"
        @keydown.delete="e => handleDelete(e, index)"
      />
    </div>
    <button
      class="get-code-btn"
      :disabled="isCounting"
      @click="handleGetCode"
    >
      {{ buttonText }}
    </button>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from 'vue';
import request from '@/utils/request'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'

import { Network } from '@capacitor/network';

// 检查当前网络状态
const checkNetwork = async () => {
  const status = await Network.getStatus();
  console.log('网络状态:', status.connected ? '已连接' : '未连接');
};

// 监听网络变化
Network.addListener('networkStatusChange', (status) => {
  console.log('网络状态变化:', status.connected);
});
// 获取路由实例
const route = useRoute()
const router = useRouter()

const phoneNumber = ref('182 3518 6061');
const codeArray = ref(Array(6).fill(''));
const isCounting = ref(false);
const countdownSecond = ref(0);
const inputRefs = ref([]);
const  requestId=ref('')

// 计算按钮文本
const buttonText = computed(() => {
  return isCounting.value 
    ? `重新获取（${countdownSecond.value}s）`
    : '获取验证码';
});

// 处理输入
const handleCodeInput = (e, index) => {
  // 过滤非数字字符
  let value = e.target.value.replace(/\D/g, '');
  codeArray.value[index] = value.slice(0, 1);

  // 自动跳转下一个输入框
  if (value && index < 5) {
    nextTick(() => {
      inputRefs.value[index + 1]?.focus();
    });
  }

  // 自动提交（当输入第四个数字时）
  if (value && index === 5) {
    handleSubmit();
  }
};

// 处理删除键
const handleDelete = (e, index) => {
  if (!codeArray.value[index] && index > 0) {
    codeArray.value[index - 1] = '';
    nextTick(() => {
      inputRefs.value[index - 1]?.focus();
    });
  }
};
// 组件挂载时获取数据
onMounted(() => {
  requestId.value=route.query.requestId
  console.log( requestId.value)
});

// 处理获取验证码
const handleGetCode = () => {
  if (isCounting.value) return;

  isCounting.value = true;
  countdownSecond.value = 60;

  const timer = setInterval(() => {
    countdownSecond.value--;
    if (countdownSecond.value <= 0) {
      clearInterval(timer);
      isCounting.value = false;
    }
  }, 1000);

  // TODO: 调用获取验证码接口
  console.log('获取验证码请求已发送');
};

// 处理验证码提交
const handleSubmit = async() => {
  const code = codeArray.value.join('');
  if (code.length === 6) {
    // TODO: 调用验证码验证接口
    console.log('提交验证码:', code);
   
    const response = await request({
      url: '/login/sendSMS',
      method: 'post',
      data: {"code":code,"phone":phoneNumber.value.trim(),"requestId":requestId.value},
      headers: {
        'Content-Type': 'multipart/form-data' // 必须设置
      }
     
    })
    console.log(response)
    if(response.data!=null){
      const token = response.data.token;
      localStorage.setItem('token', token);
      localStorage.setItem('userInfo',  JSON.stringify(response.data))
      router.push("/")

    }
  }
};

// 模拟返回上一步
const goBack = () => {
  console.log('返回上一步');
};

// 处理修改手机号
const handleModifyPhone = () => {
  console.log('处理修改手机号');
};
</script>

<style scoped>
.verify-code-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.back-btn {
  font-size: 24px;
  margin-right: 20px;
  cursor: pointer;
}

h2 {
  font-size: 24px;
  font-weight: 500;
  margin: 0;
}

.phone-info {
  margin: 20px 0;
  font-size: 16px;
  color: #666;
}

.modify-btn {
  color: #4a90e2;
  cursor: pointer;
  margin-left: 10px;
}

.code-input-box {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin: 40px 0;
}

.code-input-box input {
  width: 55px;
  height: 55px;
  border: 2px solid #ddd;
  border-radius: 12px;
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  transition: border-color 0.3s;
}

.code-input-box input:focus {
  border-color: #4a90e2;
  outline: none;
}

.get-code-btn {
  width: 100%;
  padding: 15px;
  border: none;
  border-radius: 30px;
  background-color: #4a90e2;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.get-code-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 隐藏数字输入框箭头 */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
input[type="number"] {
  -moz-appearance: textfield;
}
</style>